package data;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * The class ConnectionManager.
 */
public class ConnectionManager {

	/** */
	private static ConnectionManager connectionManager;
	
	/** */
	private Driver dBDriver = null;
	
	/** */
	private static Properties dBProperties = new Properties();

	
	/**
	 * Class constructor. Hidden.
	 */
	private ConnectionManager() {

		try {
			InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("dbconfiguration.properties");
			dBProperties.load(is);
			// dBProperties.load(new FileInputStream("dbconfiguration.properties"));
		} catch (Exception e) {
			System.err.println("El fichero de propiedades de la BDs no se ha encontrado");
			e.printStackTrace();
		}

		try {
			String driverName = dBProperties.getProperty("driverName");
			dBDriver = (Driver) Class.forName(driverName).newInstance();
			DriverManager.registerDriver(dBDriver);
		} catch (Exception e) {
			System.err.println("Unable to register JDBC Driver");
			e.printStackTrace();
		}
	}

	
	/**
	 * Gives the singleton instance of this class.
	 * 
	 * @return
	 */
	public static synchronized ConnectionManager getInstance() {
		if (connectionManager == null) {
			connectionManager = new ConnectionManager();
		}
		return connectionManager;
	}

	
	/**
	 * Creates a DB connection.
	 * 
	 * @return the created connection.
	 */
	public Connection createConnection() {
		Connection connection = null;

		try {
			String uri = dBProperties.getProperty("dBUri");
			String user = dBProperties.getProperty("username");
			String password = dBProperties.getProperty("password");
			connection = DriverManager.getConnection(uri, user, password);
		} catch (Exception e) {
			System.err.println("Unable to open a new JDBC connection");
			e.printStackTrace();
		}

		return connection;
	}

	/**
	 * Closes a DB connection.
	 * 
	 * @param connection
	 */
	public void closeConnection(Connection connection) {
		
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Finalizes the use of the DB driver.
	 */
	protected void finalize() {
		
		try {
			DriverManager.deregisterDriver(dBDriver);
		} catch (SQLException e) {
			System.err.println("Unable to deregister JDBC driver");
			e.printStackTrace();
		}
	}
}
